package com.shenmazong.serveruserapi.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.util.UUID;

/**
 * @author 田不平
 * @project server-xing-00
 * @date 2020/8/14 4:37 PM
 * http://www.shenmazong.com
 */
@Controller
@Slf4j
@ApiIgnore
public class AliyunOssController {

    @RequestMapping(value = "/")
    public String index() {
        return "index";
    }

    public String uploadAliyun(MultipartFile file, String fileName) {
        String url = null;
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。

        // shenmazong@1642590691341298.onaliyun.com
        String accessKeyId = "LTAI4G143RWPiZ3umDBvPmPE";
        String accessKeySecret = "HSvLa49rDDInMODP4AemZZaR9zG26t";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建PutObjectRequest对象。
        // 上传文件流。
        PutObjectResult result = null;
        String newName = UUID.randomUUID().toString();
        try {
            result = ossClient.putObject("shenmazong", fileName, file.getInputStream());
            url = "https://shenmazong.oss-cn-beijing.aliyuncs.com/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        // 关闭OSSClient。
        ossClient.shutdown();
        return url;
    }

    @PostMapping(value = "/upload")
    public String upload(@RequestParam("uploadFile") MultipartFile file) {
        if(file.isEmpty()){
            log.info("文件为空");
            return "index";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        log.info(fileName + "-->" + size);

        UUID uuid = UUID.randomUUID();
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String newName = uuid.toString() + suffix;

        String url = uploadAliyun(file, newName);
        if(url == null) {
            log.info("上传失败了");
            return "index";
        }
        log.info("上传成功: " + url);

        return "index";
    }
}
